package org.chnxi.algorithm.dynamic;

/**
 * 动态规划算法-背包问题
 */
public class KnapsackProblem {

    public static void main(String[] args) {
        int[] w = {1,4,3};
        int[] val = {1500,3000,2000};
        int m = 4;
        int n = val.length;

        //记录商品存放情况
        int[][] path = new int[n+1][m+1];

        //创建二位数组
        //v[i][j]表示在前i个不品种能够装入容量为j的背包中的最大价值
        //第一行和第一列均为0，不需要处理
        int[][] v = new int[n+1][m+1];

        //不处理第一行
        for(int i = 1; i < v.length; i++){
            //不处理第一列
            for (int j = 1; j < v[0].length; j++){
                if(w[i-1] > j){
                    v[i][j] = v[i-1][j];
                }else{
                    if(v[i-1][j] < val[i-1] + v[i-1][j-w[i-1]]){
                        v[i][j] = Math.max(v[i-1][j] , val[i-1] + v[i-1][j-w[i-1]]);
                        path[i][j] = 1;
                    }else{
                        v[i][j] = v[i-1][j];
                    }
                }
            }
        }

        for (int i=0; i<v.length; i++){
            for (int j=0; j<v[i].length; j++){
                System.out.print(v[i][j]+"\t");
            }
            System.out.println();
        }

        System.out.println("==============================");

        int i = path.length -1;
        int j = path[0].length -1;
        while (i>0 && j>0){
            if(path[i][j] == 1){
                System.out.println("第"+i+"个商品放入到背包");
                j -= w[i-1];
            }
            i--;
        }
    }

}
